package io.p2p.stream.p2pmain.handler;

import com.alibaba.fastjson.JSONObject;
import common.core.domain.udp.UdpApiProtocol;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.DatagramPacket;
import io.p2p.stream.p2pmain.node.ActiveNode;
import io.p2p.stream.p2pmain.session.ActiveNodeSessionManager;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ActiveNodeListHandler {
    private UdpApiProtocol apiProtocol;

    public ActiveNodeListHandler(UdpApiProtocol apiProtocol) {
        this.apiProtocol = apiProtocol;
    }

    public void activeNodeList() {

        String loginName = apiProtocol.getBuffer().getString("name");

        String clientIp = apiProtocol.getRemoteIP();
        int clientPort = apiProtocol.getRemotePort();

        Map<String, ActiveNode> activeNodeMap = ActiveNodeSessionManager.getInstance().getActiveNodeMap();
        activeNodeMap.remove(loginName);

        Collection<ActiveNode> activeNodeList = activeNodeMap.values();

        Map<String,Object> source = new HashMap<>();
        source.put("type","activeNodeListAck");
        source.put("data",activeNodeList);

        String jsonStr = JSONObject.toJSONString(source);

        apiProtocol.getCtx().writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                jsonStr, StandardCharsets.UTF_8), new InetSocketAddress(clientIp,clientPort)));
    }
}
